package cnn.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import cnn.topfox.common.SysConfigRead;
import cnn.topfox.util.CustomRedisTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;

@Configuration
public class RedisConfig {

	Jackson2JsonRedisSerializer jackson2JsonRedisSerializer2=null;
	private Jackson2JsonRedisSerializer getJacksonSerializer(){
		if (jackson2JsonRedisSerializer2==null) {
			jackson2JsonRedisSerializer2 = new Jackson2JsonRedisSerializer(Object.class);
		}

		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
		objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
		jackson2JsonRedisSerializer2.setObjectMapper(objectMapper);
		return jackson2JsonRedisSerializer2;
	}

	@Autowired(required = false) LettuceConnectionFactory redisConnectionFactory;

	@Bean("redisTemplate")//开启事务的
	public RedisTemplate<String, Object> redisTemplate() {
		RedisTemplate<String, Object> redisTemplate = new RedisTemplate();
		if (redisTemplate == null){
			return null;
		}

		redisTemplate.setConnectionFactory(redisConnectionFactory);

		redisTemplate.setEnableTransactionSupport(true);//打开事务支持
		redisTemplate.setHashKeySerializer(RedisSerializer.string());//key值始终用纯字符串序列化
		redisTemplate.setHashValueSerializer(getJacksonSerializer());
		redisTemplate.setKeySerializer(RedisSerializer.string());//key值始终用纯字符串序列化
		redisTemplate.setValueSerializer(getJacksonSerializer());
		redisTemplate.afterPropertiesSet();//初始化操作）加载配置后执行

		return redisTemplate;
	}
}